<template>
  <div class="app-container home-left_approve">
    <div class="approve-opt">
      <CustomTitle title="审批流程" />
      <div class="approve-state">
        <div
          :class="{ 'approve-state_active': statusStr == item.value }"
          v-for="item in auditStatusList"
          :key="item.value"
          @click="handelStatus(item.value)"
        >
          {{ item.label }}({{ item.count }})
        </div>
      </div>
    </div>
    <div class="approve-list">
      <div class="approve-list_header">
        <div class="custom-tabs">
          <div
            :class="{ 'custom-tabs_item-active': auditTypeStr === item.value }"
            v-for="item in auditType"
            :key="item.value"
            @click="handelAuditType(item.value)"
          >
            {{ item.label }}
          </div>
        </div>
        <a-button type="text" @click="$router.push('/audit')"
          >查看全部
          <icon-double-right />
        </a-button>
      </div>
      <div class="approve-list_state">
        <a-spin :loading="isAuditLoading">
          <template v-if="homeAuditList.length">
            <div class="approve-list_state-item" v-for="item in homeAuditList" @click="handelApproval(item)">
              <div class="item-content">
                <div class="title">{{ auditTypeStr === "mySubmit" ? item.instanceName : item.taskName }}</div>
                <!--                      <div class="title">{{item.processDefName}}</div>-->
                <div class="info">
                  发起人：{{ item?.owner?.name || item?.staterUser?.name }} |
                  {{ item.createTime || item.startTime }}
                </div>
              </div>
              <GiSvgIcon name="file-icon" size="24" />
            </div>
          </template>
          <a-empty v-else description="这里暂时什么都没有哦~">
            <template #image>
              <img :src="homeAuditIcon" alt="" />
            </template>
          </a-empty>
        </a-spin>
      </div>
    </div>
  </div>

  <a-drawer
    :visible="auditVisible"
    :footer="false"
    :width="900"
    title-align="start"
    :header="false"
    @cancel="handleDrawerCancel"
    unmountOnClose
  >
    <div class="handel-container">
      <div class="drawer-title">
        <div style="display: flex">
          <custom-title :title="drawerTitle" />
          <!--          <a-button type="text" @click="handelCheckStandard" v-show="isAcceptanceTask">查看标准</a-button>-->
        </div>
        <IconClose style="cursor: pointer" @click="handleDrawerCancel" />
      </div>
      <div class="handel-container-body">
        <div
          class="form-container"
          :style="{
            height: isAcceptanceTask ? 'calc(100vh - 113px)' : 'calc(100vh - 60px)',
            'padding-top': isAcceptanceTask ? '0px' : '20px'
          }"
        >
          <a-button type="text" style="margin: 10px 0; padding-left: 0" @click="handelCheckStandard" v-show="isAcceptanceTask"
            >查看标准</a-button
          >
          <div class="form-items" v-if="auditVisible">
            <div>审批ID：{{ auditInstanceId }}</div>
            <micro-app
              class="micro-app"
              name="form-design-home-audit"
              :url="appUrlconfig.formDesign"
              baseroute="/form-design"
              default-page="/home"
              fiber
              :data="{ token: getToken() }"
              router-mode="native"
            />
          </div>
        </div>
        <div class="followUp-container">
          <div class="followUp-header"></div>
          <div class="title">审批记录</div>
          <div class="audit-list">
            <template v-if="auditRecordList.length">
              <div class="audit-item" v-for="item in auditRecordList">
                <div class="audit-header">
                  <img :src="Avatar" alt="" />
                  <div>
                    <div class="audit-title">
                      {{ item.name }} <span>{{ item.finishTime }}</span>
                    </div>
                    <div class="audit-status">{{ auditUser(item) }}({{ auditResult(item) }})</div>
                  </div>
                </div>
                <div :class="{ 'audit-desc': true, divider: true }">
                  <div class="content" v-show="item.comment?.length">
                    <a-textarea :default-value="comment(item)" auto-size disabled />
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="audit-btn-container">
            <a-textarea v-model="commentData" placeholder="请输入审批意见" v-if="isOption" />
            <div class="form-btns" v-if="isOption">
              <!--                @click="handleDrawerCancel"-->
              <a-button style="width: 92px; background-color: #f2f3f5" type="secondary" @click="handelAuditRefuse">拒绝</a-button>
              <a-button style="width: 92px" type="primary" @click="handelAuditAgree">同意</a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-drawer>

  <!--    验收标准
    TODO:没有封装
    -->
  <a-modal v-model:visible="isShowStandard" unmount-on-close :width="900" title-align="start">
    <template #title>
      <CustomTitle title="查看" />
    </template>
    <template #footer><div></div></template>
    <a-form :model="standardForm" auto-label-width>
      <template v-for="(item, index) in standardForm.fieldData" :key="`${item.fieldName}${index}`">
        <a-form-item :label="item.fieldName" v-if="!item.valueComplex">
          <a-textarea :auto-size="{ minRows: 3 }" v-model="item.fieldValue" readonly />
        </a-form-item>
        <a-form-item v-if="item.valueComplex && item.fieldValue.length" :label="item.fieldName">
          <a-image-preview-group infinite v-if="item.fileContextType === 'image'">
            <a-space wrap>
              <a-image
                v-for="imgItem in item.fieldValue"
                :key="imgItem.fileId"
                :src="imgItem.fileUrl"
                width="80"
                height="80"
                fit="cover"
              />
            </a-space>
          </a-image-preview-group>
          <a-space wrap v-if="item.fileContextType === 'video'">
            <video
              v-for="videoItem in item.fieldValue"
              :key="videoItem.fileId"
              @click="handlePreview(videoItem.fileUrl)"
              :src="videoItem.fileUrl"
              style="width: 80px; height: 80px; object-fit: cover"
            ></video>
          </a-space>
        </a-form-item>
      </template>
    </a-form>
  </a-modal>

  <!--   预览视频 -->
  <a-modal v-model:visible="isShowPreview" unmount-on-close title-align="start" :width="900">
    <template #title>
      <CustomTitle title="视频预览" />
    </template>
    <template #footer><div></div></template>
    <video
      v-if="isShowPreview"
      :src="previewVideoUrl"
      controls
      style="width: 100%; height: 50vh; object-fit: cover; cursor: pointer"
    ></video>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import Avatar from "@/assets/images/default-avatar.png";
import homeAuditIcon from "@/assets/images/home-audit-icon.png";
import appUrlconfig from "@/config/appUrlconfig";
import { auditStatus, auditType } from "../config";
import { getToken } from "@/utils/auth";
import { mainSendForceSetData, unmountApp } from "@/microApp/utils";
import { allTaskList, allMySubmittedList } from "@/apis/home";
import { standardInfoByBusinessKey } from "@/apis";
import { handlerTask, approvalDataByInstanceId, pendingAuditList, alreadyAuditList } from "@/apis/audit";
import type { StandardForm, AuditRecordItem } from "@/apis";

const auditTypeStr = ref("myAudit");
const handelAuditType = (type: any) => {
  auditTypeStr.value = type;
  statusStr.value = "pending";
  auditStatusList.value = [...auditStatus];
  homeAuditList.value = [];
  if (type === "myAudit") {
    getAllTaskList(true);
    getPendingAuditList();
    getAlreadyAuditList();
  }
  if (type === "mySubmit") {
    getAllMySubmittedList(true);
    getPendingMySubmittedList();
    getAlreadyMySubmittedList();
  }
};

const auditStatusList = ref([...auditStatus]);
const statusStr = ref("pending");
// TODO:一坨
const handelStatus = async (status: any) => {
  statusStr.value = status;
  if (auditTypeStr.value === "myAudit") {
    if (status === "all") {
      getAllTaskList(true);
      getPendingAuditList();
      getAlreadyAuditList();
    }
    if (status === "pending") {
      getAllTaskList();
      getPendingAuditList(true);
      getAlreadyAuditList();
    }
    if (status === "already") {
      getAllTaskList();
      getPendingAuditList();
      getAlreadyAuditList(true);
    }
  }
  if (auditTypeStr.value === "mySubmit") {
    if (status === "all") {
      getAllMySubmittedList(true);
      getAllMySubmittedList();
      getAllMySubmittedList();
    }
    if (status === "pending") {
      getAllMySubmittedList();
      getPendingMySubmittedList(true);
      getAlreadyMySubmittedList();
    }
    if (status === "already") {
      getAllMySubmittedList();
      getPendingMySubmittedList();
      getAlreadyMySubmittedList(true);
    }
  }
};

/**
 * 审批流程
 */
const isAuditLoading = ref(false);
const homeAuditList = ref([]);
const params = ref({
  pageNo: 1,
  pageSize: 10
});
// 所有我审批的
const getAllTaskList = async (isGetData?: boolean) => {
  try {
    // isAuditLoading.value = true;
    const { data } = await allTaskList();
    isAuditLoading.value = false;
    if (isGetData) {
      homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
    }
    auditStatusList.value[0].count = data?.total || 0;
  } catch (err) {
    isAuditLoading.value = false;
  }
};
// 待我处理
const getPendingAuditList = async (isGetData?: boolean) => {
  const { data } = await pendingAuditList(params.value);
  if (isGetData) {
    homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
  }
  auditStatusList.value[1].count = data?.total || 0;
};
// 我已处理
const getAlreadyAuditList = async (isGetData?: boolean) => {
  const { data } = await alreadyAuditList(params.value);
  if (isGetData) {
    homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
  }
  auditStatusList.value[2].count = data?.total || 0;
};
// 我发起的
const getAllMySubmittedList = async (isGetData?: boolean) => {
  const mySubmitParam = {
    pageNo: 1,
    pageSize: 10
  };
  const { data } = await allMySubmittedList(mySubmitParam);
  if (isGetData) {
    homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
  }
  auditStatusList.value[0].count = data?.total || 0;
};
const getAlreadyMySubmittedList = async (isGetData?: boolean) => {
  const mySubmitParam = {
    pageNo: 1,
    pageSize: 10,
    finished: true
  };
  const { data } = await allMySubmittedList(mySubmitParam);
  if (isGetData) {
    homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
  }
  auditStatusList.value[2].count = data?.total || 0;
};
const getPendingMySubmittedList = async (isGetData?: boolean) => {
  const mySubmitParam = {
    pageNo: 1,
    pageSize: 10,
    finished: false
  };
  const { data } = await allMySubmittedList(mySubmitParam);
  if (isGetData) {
    homeAuditList.value = data?.records ? data?.records.slice(0, 3) : [];
  }
  auditStatusList.value[1].count = data?.total || 0;
};

/**
 * 审批
 */
const auditVisible = ref(false);
const drawerTitle = ref("");
const auditInstanceId = ref("");
const isOption = ref(false);
const auditRecordList = ref<AuditRecordItem[]>([]);
const auditStatusMap = new Map([
  ["complete", "发起申请"],
  ["refuse", "已拒绝"],
  ["agree", "已同意"]
]);
// TODO:计算属性传参问题
const auditResult = computed(() => {
  return (data: any) => {
    if (!data?.result) {
      return "审批中";
    }
    return auditStatusMap.get(data.result) || "";
  };
});
const auditUser = computed(() => {
  return (data: any) => {
    return data.user?.name || "";
  };
});
const comment = computed(() => {
  return (data: any) => {
    return data?.comment?.length ? data?.comment[0]?.text : "";
  };
});
const handelApproval = (auditData: any) => {
  auditVisible.value = true;
  drawerTitle.value = auditData.taskName;
  auditPostData.value.instanceId = auditData.instanceId;
  auditPostData.value.taskId = auditData.taskId;
  auditPostData.value.nodeId = auditData.nodeId;
  isOption.value = auditTypeStr.value === "myAudit" && !auditData.taskResult;
  getApprovalDataByInstanceId(auditData.processDefId, auditData.instanceId);
  mainSendForceSetData("form-design-home-audit", {
    auditData,
    isHomeAudit: true // 表单禁用
  });
};
const getApprovalDataByInstanceId = async (defId: string, instanceId: string) => {
  const { data } = await approvalDataByInstanceId(defId, instanceId);
  auditInstanceId.value = data?.instanceId ?? "";
  isAcceptanceTask.value = data?.formId && data.formId.includes("acceptance");
  businessKey.value = data?.processProgressVo?.businessKey || "";
  auditRecordList.value = data?.processProgressVo?.progress || [];
  auditPostData.value.formData = data?.formData || {};
};

/**
 * 验收审批-查看验收标准
 */
const isShowStandard = ref(false);
const isAcceptanceTask = ref(false);
const isShowPreview = ref(false);
const businessKey = ref("");
const standardForm = ref<StandardForm>({
  imageList: [],
  videoList: [],
  fieldData: []
});
const previewVideoUrl = ref("");
const handelCheckStandard = async () => {
  const { data } = await standardInfoByBusinessKey(businessKey.value);
  if (!data) return Message.error("数据错误");
  standardForm.value.fieldData = data || [];
  isShowStandard.value = true;
};
const handlePreview = (url: string) => {
  previewVideoUrl.value = url;
  isShowPreview.value = true;
};

/**
 * 提交审批
 */
const commentData = ref("");
const auditPostData = ref<any>({});
const handelAuditAgree = async () => {
  auditPostData.value.action = "agree";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  initData();
  handleDrawerCancel();
  Message.success("操作成功");
};
const handelAuditRefuse = async () => {
  auditPostData.value.action = "refuse";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  initData();
  handleDrawerCancel();
  Message.success("操作成功");
};
const handleDrawerCancel = () => {
  auditVisible.value = false;
  commentData.value = "";
  auditPostData.value = {};
  auditRecordList.value = [];
  unmountApp("form-design-audit");
};

const initData = () => {
  getAllTaskList();
  getPendingAuditList(true);
  getAlreadyAuditList();
};

initData();
</script>

<style scoped lang="scss">
.home-left {
  @include flex;
  flex-direction: column;
  flex: 1;
  margin-right: 20px;

  &_info {
    @include flex;
    margin-bottom: 20px;
  }

  &_user {
    @include flex-center;
    flex-direction: column;
    width: 283px;
    padding: 26px 0;
    margin-right: 20px;
    background: url("@/assets/images/home-avatar-bg.png") no-repeat;
    background-size: 100% 100%;
    text-align: center;

    .user-avatar {
      @include flex-center;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background-color: #fff;
    }

    .user-name {
      margin: 20px auto 5px;
      font-weight: 700;
      font-size: 16px;
      color: #3d3d3d;
      line-height: 23px;
    }

    .user-dept {
      font-size: 14px;
      color: #767676;
      line-height: 20px;
    }
  }

  &_approve {
    @include flex;
    flex: 1;
    background: #fff;
    box-shadow: 4px 5px 16px 0 rgba(4, 19, 74, 0.04);
    border-radius: 10px;
  }

  .approve-opt {
    padding-right: 20px;

    .title {
      padding-top: 4px;
    }

    .approve-state {
      @include flex;
      flex-direction: column;
      padding-right: 20px;
      margin-top: 20px;
      border-right: 1px solid #c2d4e8;

      div {
        @include flex-inline-flex;
        width: 95px;
        height: 28px;
        background-color: #f5f7fa;
        border-radius: 32px;
        cursor: pointer;

        & + div {
          margin-top: 32px;
        }
      }

      .approve-state_active {
        background: #007dff;
        color: #fff;
      }
    }
  }

  .approve-list {
    flex: 1;
    display: flex;
    flex-direction: column;

    &_header {
      @include flex-between;
      margin-bottom: 12px;
    }

    &_state {
      flex: 1;
      position: relative;
      &-item {
        @include flex-between;
        align-items: center;
        padding: 4px 20px;
        box-sizing: border-box;
        background-color: #f5f7fa;
        border-radius: 4px;
        cursor: pointer;

        & + .approve-list_state-item {
          margin-top: 4px;
        }

        .item-content {
          .title {
            margin-bottom: 3px;
            font-size: 14px;
            color: #3d3d3d;
            line-height: 20px;
          }

          .info {
            font-size: 12px;
            color: #989ea8;
            line-height: 17px;
          }
        }
      }
      :deep(.arco-empty) {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    :deep(.arco-spin) {
      width: 100%;
    }
  }
}

.handel-container {
  height: inherit;
  .drawer-title {
    @include flex-between;
    align-items: center;
    padding-bottom: 12px;
    border-bottom: 1px solid #dcdfe6;
  }
  &-body {
    @include flex;
  }

  .form-container {
    height: 100%;
    width: 50%;
    box-sizing: border-box;
    border-right: 1px solid #dcdfe6;
    padding-right: 16px;
    padding-top: 20px;
  }

  .followUp-container {
    width: 50%;
    box-sizing: border-box;
    padding-left: 16px;
    position: relative;
  }

  .form-items {
    height: calc(100vh - 113px);
    overflow-y: auto;
    padding: 10px;
    box-sizing: border-box;
    background-color: #f6f8fa;
    border: 1px solid #dcdfe6;

    .micro-app,
    :deep(micro-app-body) {
      min-width: 100% !important;
    }
  }

  .followUp-header {
    @include flex-between;
    margin-bottom: 24px;
  }

  .audit-list {
    max-height: 60vh;
    overflow-y: scroll;
    margin: 30px 0;
    padding-right: 10px;

    .audit-item {
      .audit-header {
        display: flex;
        align-items: center;

        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }

        > div {
          margin-left: 16px;
          width: 100%;

          .audit-title {
            display: flex;
            justify-content: space-between;
          }
        }
      }

      .audit-desc,
      .audit-status,
      .content,
      span {
        color: #86909c;
        font-size: 12px;
      }

      .audit-desc,
      .divider {
        margin-left: 20px;
        border-left: 1px solid rgb(var(--gray-2));
      }

      .divider {
        height: 90px;
      }

      .audit-desc {
        //padding: 10px 0 10px 36px;
        box-sizing: border-box;

        .content {
          //background: rgb(var(--gray-3));
          width: 100%;
          border-radius: 4px;
          padding: 12px;
          box-sizing: border-box;
        }
      }
    }
  }

  .audit-btn-container {
    width: calc(100% - 40px);
    position: absolute;
    bottom: 10px;
    left: 20px;
  }

  .form-btns {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    gap: 20px;
  }
}
</style>
